package handler

import (
	"fmt"
	"multi-cloud-manage/config"
	"multi-cloud-manage/internal/model"
	"multi-cloud-manage/internal/storage"
	"multi-cloud-manage/utils"
	"time"

	"github.com/gin-gonic/gin"
)

// 添加凭证
func AddCredentials(c *gin.Context) {
	// 获取传递的参数
	provider := c.PostForm("provider")
	ak := c.PostForm("ak")
	sk := c.PostForm("sk")
	if provider == "" || ak == "" || sk == "" {
		c.JSON(200, gin.H{
			"code":    401,
			"message": "提供商、ak、sk均不能为空",
		})
		return
	}
	// 对AK，SK进行加密
	encryptedAK, err := utils.GcmEncrypt(config.GetConfig().Aescrypt.Key, ak)
	if err != nil {
		c.JSON(200, gin.H{
			"code":    402,
			"message": "加密失败",
		})
		return
	}
	encryptedSK, _ := utils.GcmEncrypt(config.GetConfig().Aescrypt.Key, sk)
	fmt.Println("加密的ak：", encryptedAK)
	fmt.Println("加密的sk：", encryptedSK)
	// 获取当前用户的id
	value, _ := c.Get("userID")
	// 类型断言
	v := value.(int)
	userCredentials := model.UserCredentials{
		Provider: provider,
		AK:       encryptedAK,
		SK:       encryptedSK,
		CreateAt: time.Now(),
		UserId:   v,
	}
	err = storage.CreateCredentials(&userCredentials)
	if err != nil {
		c.JSON(200, gin.H{
			"code":    403,
			"message": "凭据添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code":    200,
		"message": "凭据添加成功",
	})
}
